﻿#include "login.h"
#include "ui_login.h"

login::login(QWidget *parent,QString db_name) :
    QWidget(parent),
    user_info_db (new user_db(db_name)),
    ui(new Ui::login)
{
    ui->setupUi(this);

    //初始化数据库，创建用户表
    setWindowTitle(QStringLiteral("登录"));
}

login::~login()
{
    delete ui;
}

char login::Check_Legality()
{
    login_user =  ui->lineEdit->text();
    add_log("logoin_user:", login_user);
    login_password =  ui->lineEdit_2->text();
    add_log("login_password:", login_password);
    bool val = false;
    if (login_user.isEmpty()){
        QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("用户名不能为空！"));
        val = false;
    }
    else if (login_password.isEmpty()){
        QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("密码不能为空！"));
        val = false;
    }
    else
        val = true;
    return val;
}

void login::on_pushButton_clicked()
/*
 * 登录按钮
 * 1、确定数据库是否有名字，没有则需要新建；
 * 2、确定有名字后验证密码是否正确；
 * 3、登录后，如果没有簿子，则需要新建簿子数据库。簿子数据库默认命名为账户名+gf.db
 */
{
    char val = -1;
    val = Check_Legality();

    if (val) {
       val = user_info_db->user_login_check(login_user,login_password);
       if (val == 2)  //如果密码和用户都存在
       {
           QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("登录成功！"));
           add_log(login_user,QStringLiteral("登录成功！"));
           QString user_acc_name = login_user+"_account_data";

           account_info_db = new account_db(user_acc_name);
           emit login_success(login_user,account_info_db);
       }
       else if (val == 1)
           QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("密码错误！"));
       else
           QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("不存在用户名！"));
    }
}

void login::on_pushButton_3_clicked()
/*
 * 注册账号按钮
 *
 */
{
    bool val=0;
    char insert_info = 0;
    val = Check_Legality();

    if (val) {
       insert_info = user_info_db->user_insert_info(login_user,login_password);
       switch (insert_info) {
       case user_info_db->I_EXIST:
           QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("用户名已存在！请勿重复创建"));
       break;
       case user_info_db->I_FALSE:
           QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("创建失败！"));
       break;
       case user_info_db->I_SUCCESS:
           QMessageBox::information(this,QStringLiteral("提示"),QStringLiteral("用户创建成功！"));
           break;
       }
    }
}

